/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ExJoInsertPanel.java
 *
 * Created on 29/11/2011, 22:59:22
 */

package proj5labbd.graphics.exibicaoJornal;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;


public class ExJoInsertPanel extends OperationPanel {

    /** Creates new form ExJoInsertPanel */
    public ExJoInsertPanel(ExJoFrame frame, DBInterface dbInterface) {
        super(frame, dbInterface);
        initComponents();
        jbtInsert.addActionListener(new JornalAction());
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbData = new javax.swing.JLabel();
        jlbHoraIn = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbJornal = new javax.swing.JTable();
        jlbJornal = new javax.swing.JLabel();
        jlbFuncionario = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtFuncionario = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jlbIbope = new javax.swing.JLabel();
        jtxtIbope = new javax.swing.JTextField();
        jftxtDate = new javax.swing.JFormattedTextField();
        jftxtIni = new javax.swing.JFormattedTextField();
        jftxtFim = new javax.swing.JFormattedTextField();
        jbtInsert = new javax.swing.JButton();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Inserção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros de inserção"));

        jlbData.setText("Data");

        jlbHoraIn.setText("Hora de início");

        jtbJornal.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jtbJornal.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jtbJornal);

        jlbJornal.setText("Jornal");

        jlbFuncionario.setText("Apresentador");

        jtFuncionario.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(jtFuncionario);

        jLabel1.setText("Hora de término");

        jlbIbope.setText("Ibope");

        try {
            jftxtDate.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-##-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtDate.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtIni.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtIni.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        try {
            jftxtFim.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##:##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtFim.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jlbFuncionario, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 723, Short.MAX_VALUE)
                    .addComponent(jlbJornal, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jpnParamLayout.createSequentialGroup()
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbData, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(8, 8, 8)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jftxtIni, 0, 0, Short.MAX_VALUE)
                            .addComponent(jlbHoraIn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jftxtFim, 0, 0, Short.MAX_VALUE)
                            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jtxtIbope, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jlbIbope, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE)))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 723, Short.MAX_VALUE))
                .addContainerGap())
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbData)
                    .addComponent(jlbHoraIn)
                    .addComponent(jLabel1)
                    .addComponent(jlbIbope))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jftxtDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtIni, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtFim, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtIbope, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jlbJornal)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jlbFuncionario, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(253, 253, 253))
        );

        jbtInsert.setText("Inserção");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(12, 12, 12))
                    .addComponent(jbtInsert, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, 503, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addComponent(jbtInsert))
        );
    }// </editor-fold>//GEN-END:initComponents

    /*
     * Resgata as informações das tabelas que serão exibidas
     */
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        try {
            // TODO add your handling code here:
            setupTables();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível resgatar as informações das tabelas");
            frame.printException(ex);
        }
    }//GEN-LAST:event_formComponentShown

    /*
     * Trata eventos do mouse
     */
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbJornal.clearSelection();
        jtFuncionario.clearSelection();
    }//GEN-LAST:event_formMouseClicked


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton jbtInsert;
    private javax.swing.JFormattedTextField jftxtDate;
    private javax.swing.JFormattedTextField jftxtFim;
    private javax.swing.JFormattedTextField jftxtIni;
    private javax.swing.JLabel jlbData;
    private javax.swing.JLabel jlbFuncionario;
    private javax.swing.JLabel jlbHoraIn;
    private javax.swing.JLabel jlbIbope;
    private javax.swing.JLabel jlbJornal;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtFuncionario;
    private javax.swing.JTable jtbJornal;
    private javax.swing.JTextField jtxtIbope;
    // End of variables declaration//GEN-END:variables

    class JornalAction implements ActionListener {

        /*
         * Controla os eventos de inserção
         */
        public void actionPerformed(ActionEvent e) {
            if ( jtFuncionario.getSelectedRowCount() == 1 && jtbJornal.getSelectedRowCount() == 1 &&
                    jftxtDate.getText() != "  -  -    " && jftxtIni.getText() != "  :  ") {
                    ArrayList<String> params = new ArrayList<String>();
                    ArrayList<String> fields = new ArrayList<String>();

                    params.add((String)jtbJornal.getValueAt(jtbJornal.getSelectedRow(), 0));
                    fields.add("idPr");
                    params.add("TO_DATE('"+jftxtDate.getText()+"','DD-MM-YYYY')");
                    fields.add("dataExJo");

                    params.add("'"+jftxtIni.getText()+"'");
                    fields.add("horaInicioExJo");

                    if (jftxtFim.getText() != "  :  ") {
                        params.add("'"+jftxtFim.getText()+"'");
                        fields.add("horaFimExJo");
                    }

                    if (jtxtIbope.getText() != "") {
                        params.add("'"+jtxtIbope.getText()+"'");
                        fields.add("ibopeExJo");
                    }

                    params.add((String)jtFuncionario.getValueAt(jtFuncionario.getSelectedRow(), 0));
                    fields.add("idFu");

                    String [] paramArray = new String[params.size()];
                    String [] fieldArray = new String[fields.size()];

                    params.toArray(paramArray);
                    fields.toArray(fieldArray);
                    try {
                        dbInterface.insert(fieldArray, paramArray, new String[]{"exibicaoJornal"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao tentar inserir a tupla.");
                    }

                }
                else if (jtFuncionario.getSelectedRowCount() != 1 && jtFuncionario.getSelectedRow() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve escolher um apresentador e o programa referente à exibição.");
                }
                else if (jftxtDate.getText() == "  -  -    ") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir uma data da exibição.");
                }
                else if (jftxtIni.getText() == "  :  ") {
                    JOptionPane.showMessageDialog(null, "Você deve inserir um horário de inicio da exibição.");
                }
        }
        }

    /*
     * Formata as tabelas funcionario e jornal para serem exibidas
     */
    private void setupTables() throws SQLException {
        String[] title1 = {"ID","CPF", "Nome completo", "Tipo"};
        String[] field1 = {"funcionario.idFu","funcionario.cpfFu", "funcionario.nomeCompletoFu", "tipoFuncionario.descricaoTipoFu"};
        String [] params = {"funcionario.idTipoFu=tipoFuncionario.idTipoFu"};
        String[] table1 = {"funcionario", "tipoFuncionario"};
        DefaultTableModel model = new DefaultTableModel(dbInterface.view(field1, params, table1), title1);
        jtFuncionario.setModel(model);
        jtFuncionario.setRowSelectionAllowed(true);
        String[] title2 = {"ID", "Título"};
        String[] field2 = {"idPr", "tituloPr"};
        String[] table2 = {"jornal"};
        model = new DefaultTableModel(dbInterface.view(field2, null, table2), title2);
        jtbJornal.setModel(model);
        jtbJornal.setRowSelectionAllowed(true);
    }

}
